import threading
import time
from socket import socket

import psutil
from typing import List
from datetime import datetime
import socket

from app.modle.models import NIC, NetworkInfo, NetworkInterface
from app.utils.util import bytes_to_mb
from app.setting.config import MAX_HISTORY
from app.utils.util import get_current_time

class NetworkMonitor:

    def __init__(self):
        self.network_history = []
        self.time_history = []
        self.max_history = 60
        self.last_network_io = None
        self._lock = threading.Lock()
        self.last_cache = None  # 新增缓存属性
    # def get_nic_info(self) -> List[NIC]:
    #     """采集所有网络接口的详细信息（映射到NIC模型）"""
    #     nic_list = []
    #     interfaces = netifaces.interfaces()  # 获取所有接口名称（如eth0、Wi-Fi）
    #     if_stats = psutil.net_if_stats()  # 获取接口状态（MTU、是否激活等）
    #
    #     for iface in interfaces:
    #         nic = NIC(
    #             nic_name=iface,
    #             nic_timestamp=datetime.datetime.now()
    #         )
    #
    #         # 1. 解析地址、子网掩码、广播、点对点地址（利用netifaces）
    #         addr_data = netifaces.ifaddresses(iface)
    #         family_map = {  # 地址族映射（netifaces常量→易读名称）
    #             netifaces.AF_INET: 'IPv4',
    #             netifaces.AF_INET6: 'IPv6',
    #             netifaces.AF_LINK: 'MAC'
    #         }
    #
    #         for family, addr_list in addr_data.items():
    #             family_name = family_map.get(family, f"AF_{family}")
    #             addresses, netmasks, broadcasts, ptp = [], [], [], []
    #
    #             for addr in addr_list:
    #                 addresses.append(addr.get('addr', ''))
    #                 netmasks.append(addr.get('netmask', ''))
    #                 broadcasts.append(addr.get('broadcast', ''))
    #                 ptp.append(addr.get('peer', ''))  # 点对点地址（如PPP连接）
    #
    #             # 去重后赋值（避免重复数据）
    #             if addresses:
    #                 nic.nic_address[family_name] = list(set(addresses))
    #             if netmasks:
    #                 nic.nic_netmask[family_name] = list(set(netmasks))
    #             if broadcasts:
    #                 nic.nic_broadcast[family_name] = list(set(broadcasts))
    #             if ptp:
    #                 nic.nic_ptp[family_name] = list(set(ptp))
    #
    #         # 2. 解析接口状态、MTU、双工、带宽（利用psutil）
    #         if iface in if_stats:
    #             stats = if_stats[iface]
    #             nic.nic_is_up = stats.isup
    #             nic.nic_mtu = stats.mtu
    #             # 双工模式：兼容不同系统的返回值（如Windows可能为None）
    #             nic.nic_duplex = stats.duplex.lower() if (stats.duplex and stats.duplex != 'UNKNOWN') else 'unknown'
    #             nic.nic_speed = stats.speed  # 单位：Mbps
    #         nic_list.append(nic)
    #     return nic_list

    async def get_network_info(self) -> NetworkInfo:
        """获取网络使用情况"""
        """获取网络使用情况"""
        try:
            # 获取网络IO统计
            network_io = psutil.net_io_counters()

            # 计算网络速度
            if self.last_network_io is None:
                self.last_network_io = (network_io, time.time())
                speed_kb = 0
            else:
                last_io, last_time = self.last_network_io
                time_delta = time.time() - last_time

                bytes_sent_delta = network_io.bytes_sent - last_io.bytes_sent
                bytes_recv_delta = network_io.bytes_recv - last_io.bytes_recv

                speed_kb = round((bytes_sent_delta + bytes_recv_delta) / time_delta / 1024, 2)
                self.last_network_io = (network_io, time.time())

            # 获取网络接口信息
            interfaces = []
            for interface, addrs in psutil.net_if_addrs().items():
                if interface != 'lo':  # 跳过回环接口
                    for addr in addrs:
                        if addr.family == socket.AF_INET:  # IPv4
                            interfaces.append(NetworkInterface(
                                name=interface,
                                ip=addr.address,
                                netmask=addr.netmask or ""
                            ))
                            break

            with self._lock:
                self.network_history.append(speed_kb)
                self.time_history.append(get_current_time())
                if len(self.network_history) > MAX_HISTORY:
                    self.network_history.pop(0)
                    self.time_history.pop(0)

            network_info = NetworkInfo(
                bytes_sent=bytes_to_mb(network_io.bytes_sent),
                bytes_recv=bytes_to_mb(network_io.bytes_recv),
                packets_sent=network_io.packets_sent,
                packets_recv=network_io.packets_recv,
                speed_kb=speed_kb,
                interfaces=interfaces,
            )
            self.last_cache = network_info  # 更新缓存
            return network_info
        except Exception as e:
            print(f"获取网络信息失败: {e}")
            return NetworkInfo(
                bytes_sent=0.0,
                bytes_recv=0.0,
                packets_sent=0,
                packets_recv=0,
                speed_mb=0.0,
                interfaces=[],
            )




if __name__ == '__main__':
    monitor = NetworkMonitor()
    print(monitor.get_network_info().json())